package com.offcn.sellergood.controller;


import com.offcn.entity.Result;
import com.offcn.entity.StatusCode;
import com.offcn.sellergood.utils.FastDFSClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class UploadController {

    @Value("${file.url}")
    public String url;

    @PostMapping("/upload")
    /*@RequestParam(“页面的关键字”):用于传参，实现参数名称不一致时的名称匹配操作。传的是从页面的来的关键字。*/
    public Result upload(@RequestParam("file") MultipartFile file) {
        // 文件原始名
        String originalFilename = file.getOriginalFilename();
        // 获取文件的后缀名
        String ext = StringUtils.getFilenameExtension(originalFilename);

        // 创建工具类对象
        try {
            FastDFSClient fastDFSClient = new FastDFSClient("classpath:fdfs_client.conf");
            String path = fastDFSClient.uploadFile(file.getBytes(), ext);
            String fileUrl = url + path;
            return new Result(true, StatusCode.OK,"上传成功",fileUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR,"上传失败",null);
        }


    }

}
